/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-04-06 13:13:27
 * @LastEditTime: 2022-04-20 16:30:14
 */

import React, { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import { ManageRuleReducer } from '../reducers/ManageRuleReducer';
import {
  ADD_RULE,
  DELETE_RULE,
  DELETE_RULE_USER,
  INIT_SELECTED_LIST,
  SAVE_USER_RIGHTS,
  SET_RULE_LIST,
  SET_RULE_SELECTED_ITEM,
  SET_RULE_USER_LIST,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL,
  SET_USER_RIGHTS_INFO,
  SET_USER_SELECTED_ITEM
} from '../constants';
import {
  createManageRightRule,
  deleteManageRightRule,
  deleteManageRuleUser,
  fetchManageRightRuleListByPage,
  fetchManageRuleUser,
  fetchManageUserRights,
  saveManageUserRights
} from '@/api/right';

const initialState = {
  // 当前选中的项目
  selectUnit: {},
  selectFond: {},
  selectAT: {},
  selectLevel: {},

  // 规则列表
  ruleList: [],
  // 所使用的用户和组列表
  userList: [],
  // 用户表格动态表头列表
  userTableTitles: [],

  // 选中的表格条目
  ruleSelectItems: [],
  // 选中的表格条目
  userSelectItems: [],

  // 编辑用户权限
  userRightsInfo: {}
};

const ManageRuleContext = createContext();

const ManageRuleContextProvider = (props) => {
  const [state, dispatch] = useReducer(ManageRuleReducer, initialState);

  const actions = {
    /**
     * @description: 打开新增全宗弹窗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 设置规则表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setRuleSelectItems(selectArr) {
      dispatch({ type: SET_RULE_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 设置规则表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setUserSelectItems(selectArr) {
      dispatch({ type: SET_USER_SELECTED_ITEM, data: selectArr });
    },

    getRightSpecList(query) {
      return new Promise((resolve, reject) => {
        fetchManageRightRuleListByPage(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_RULE_LIST, data: data.results });
            dispatch({ type: INIT_SELECTED_LIST });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 添加规则
     * @param {*} data 请求参数
     */
    addRightSpecFunc(data) {
      return new Promise((resolve, reject) => {
        createManageRightRule(data)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_RULE, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除规则
     * @param {number|number[]} id 删除规则的id
     */
    deleteRightSpecFunc(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除选中的规则？',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteManageRightRule(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_RULE, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 获取规则下用户列表
     * @param {*} id 规则
     */
    getSpecUserList(id) {
      fetchManageRuleUser(id)
        .then((res) => {
          const { data } = res;
          dispatch({ type: SET_RULE_USER_LIST, data });
        })
        .catch((err) => {
          console.warn('err:', err);
        });
    },

    /**
     * @description: 更新规则下用户列表
     * @param {*} data 更新后的用户列表及动态权限组成的对象
     */
    updateSpecUserList(data) {
      dispatch({ type: SET_RULE_USER_LIST, data });
    },

    /**
     * @description: 删除规则下的用户、组
     * @param {number|number[]} id 删除用户、组的id
     */
    deleteSpecUser(id) {
      Modal.confirm({
        title: '删除',
        content: '确认删除选中的用户、组？',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteManageRuleUser(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_RULE_USER, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    getUserRights(id) {
      return new Promise((resolve, reject) => {
        fetchManageUserRights(id)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_USER_RIGHTS_INFO, data });
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },

    saveUserRightsFunc(params) {
      return new Promise((resolve, reject) => {
        saveManageUserRights(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SAVE_USER_RIGHTS, data });
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {
    if (state.ruleSelectItems.length > 0) {
      actions.getSpecUserList(state.ruleSelectItems[0]);
    }
  }, [state.ruleSelectItems]);

  return (
    <ManageRuleContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </ManageRuleContext.Provider>
  );
};

export const useManageRuleContext = () => {
  return useContext(ManageRuleContext);
};

export { ManageRuleContext, ManageRuleContextProvider };
